package com.example.readroomforpaging3.ui.fragment

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.AttrRes
import androidx.annotation.ColorInt
import androidx.core.content.res.use
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.ExperimentalPagingApi
import com.example.readroomforpaging3.R
import com.example.readroomforpaging3.adapter.ViewPagerAdapter
import com.example.readroomforpaging3.databinding.FragmentDetailBinding
import com.example.readroomforpaging3.viewmodel.ArticleViewModel
import com.example.readroomforpaging3.viewmodel.ViewModelFactory
import com.google.android.material.transition.MaterialContainerTransform
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch


class DetailFragment : Fragment() {

    private val viewModel by activityViewModels<ArticleViewModel> {
        ViewModelFactory(requireActivity())
    }

    private val viewPagerAdapter by lazy {
        ViewPagerAdapter()
    }

    private var _binding: FragmentDetailBinding? = null
    private val binding get() = _binding!!

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d("TAG", "DetailFragment: $viewModel")

        sharedElementEnterTransition = MaterialContainerTransform().apply {
            drawingViewId = R.id.fragment
            duration = 300.toLong()
            scrimColor = Color.TRANSPARENT
            setAllContainerColors(requireContext().themeColor(R.attr.colorSurface))
        }
    }

    @ExperimentalPagingApi
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentDetailBinding.inflate(inflater)
        viewLifecycleOwner.lifecycleScope.launch {
            viewModel.articlePage.collectLatest {
                viewPagerAdapter.submitData(it)
            }
        }
        val position = arguments?.getInt("position") ?: 0
        val viewPager = binding.viewPager
        viewPager.adapter = viewPagerAdapter
        viewPager.setCurrentItem(position, false)
        return binding.root
    }
}

@ColorInt
@SuppressLint("Recycle")
fun Context.themeColor(
    @AttrRes themeAttrId: Int
): Int {
    return obtainStyledAttributes(
        intArrayOf(themeAttrId)
    ).use {
        it.getColor(0, Color.MAGENTA)
    }
}